﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;

namespace MockupDesigner.AppItems.Commands
{
    public class DragCommand : ICommand
    {

        public CommandType CommandType
        {
            get { return CommandType.Undoable; }
        }

        public void Execute(object target, params object[] parameters)
        {
            Redo();
        }

        public void Redo()
        {
            if (positions == null)
                return;
            foreach (DesignerItem item in positions.Keys)
            {
                Canvas.SetLeft(item, positions[item].X + deltaX <0 ? 0 : positions[item].X + deltaX);
                Canvas.SetTop(item, positions[item].Y + deltaY <0 ? 0 : positions[item].Y + deltaY);
            }
        }

        public void Undo()
        {
            if (positions == null)
                return;
            foreach (DesignerItem item in positions.Keys)
            {
                Canvas.SetLeft(item, positions[item].X);
                Canvas.SetTop(item, positions[item].Y);
            }
        }

        private Dictionary<DesignerItem, Point> positions;
        private double deltaX;
        private double deltaY;

        public void SetInitialPositions(DesignerCanvas designerCanvas, DesignerItem designerItem)
        {
            if (this.positions == null && designerCanvas != null && designerItem.IsSelected)
            {
                // we only move DesignerItems
                var designerItems = designerCanvas.SelectionService.CurrentSelection.OfType<DesignerItem>();
                this.positions = new Dictionary<DesignerItem, Point>();
                foreach (DesignerItem item in designerItems)
                {
                    if (!positions.ContainsKey(item))
                    {
                        double left = Canvas.GetLeft(item);
                        double top = Canvas.GetTop(item);
                        positions.Add(item, new Point(double.IsNaN(left) ? 0 : left, double.IsNaN(top) ? 0 : top));
                    }
                }
            }
        }

        public void SetFinalDelta(double deltaX, double deltaY)
        {
            this.deltaX = deltaX;
            this.deltaY = deltaY;
        }
    }
}
